<?php

namespace App\Remote\Feishu\Auth;

use App\Remote\Feishu\Sso\SsoRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\ValidationException;
use Psr\SimpleCache\InvalidArgumentException;
use Symfony\Component\HttpFoundation\Request as RequestAlias;

class TenantAccessTokenRemote extends Remote
{

    /**
     *
     * 获取应用token
     *
     * @param int $appType
     * @return mixed
     * @throws GuzzleException
     * @throws InvalidArgumentException
     * @throws ValidationException
     */
    public static function accessToken(int $appType)
    {
        $cacheKey    = "appType:{$appType}:accessToken";
        $redis       = Cache::store("redis");
        $accessToken = $redis->get($cacheKey);
        if (empty($accessToken)) {
            list($clientId, $clientSecret) = SsoRemote::getOauthTypeConfig($appType);
            $accessToken = self::customRequestV3(
                "/open-apis/auth/v3/tenant_access_token/internal",
                RequestAlias::METHOD_POST,
                [
                    "app_id"     => $clientId,
                    "app_secret" => $clientSecret
                ],
                ["Content-Type" => "application/json"]
            );
            if (($expire = $accessToken["expire"] - 10) > 0) {
                $redis->set($cacheKey, json_encode($accessToken, JSON_UNESCAPED_UNICODE), $expire);
            }
        } else {
            $accessToken = json_decode($accessToken, true);
        }
        return $accessToken;
    }

}
